package com.cwt.service.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cwt.common.constant.SysConstant;
import com.cwt.common.result.AjaxResult;
import com.cwt.service.domain.SysMenu;
import com.cwt.service.domain.vo.MenuTreeVo;
import com.cwt.service.domain.vo.RoleMenuVo;
import com.cwt.service.service.SysMenuService;
import com.cwt.service.mapper.SysMenuMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Acer
* @description 针对表【sys_menu(系统菜单/权限表)】的数据库操作Service实现
* @createDate 2023-07-19 11:55:23
*/
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
    implements SysMenuService{

    @Override
    public List<MenuTreeVo> selectMenuTree(Integer id) {
        List<MenuTreeVo> treeVos = baseMapper.selectMenuTree(id);
        List<MenuTreeVo> mTrees = treeVos.stream().filter(menu -> "M".equals(menu.getMenuType())).collect(Collectors.toList());
        List<String> menuIds = new ArrayList<>(); // 已处理id集合
        mTrees.forEach(mTree -> {
            List<MenuTreeVo> children = buildMenuTree(mTree.getId(), treeVos, menuIds);
            children.forEach(child -> child.setParentName(mTree.getName()));
            mTree.setChildren(children);
        });
        return mTrees;
    }

    private List<MenuTreeVo> buildMenuTree(String parentId, List<MenuTreeVo> menus, List<String> menuIds) {
        menuIds.add(parentId);
        List<MenuTreeVo> children = new ArrayList<>();
        for (MenuTreeVo menu : menus) {
            if (menu.getParentId().equals(parentId)) {
                children.add(menu);
            }
            if ("F".equals(menu.getMenuType()) || menuIds.contains(menu.getId())) {
                continue;
            }
            List<MenuTreeVo> childes = buildMenuTree(menu.getId(), menus, menuIds);
            childes.forEach(child -> child.setParentName(menu.getName()));
            menu.setChildren(childes);
        }
        return children;
    }

    @Override
    public AjaxResult allRoleMenus() {
        List<RoleMenuVo> menuVos = baseMapper.roleMenus(0);
        menuVos.forEach(menu -> {
            menu.setChildren(baseMapper.roleMenus(menu.getId()));
        });
        return AjaxResult.success(new RoleMenuVo(SysConstant.ALL_ROLE_ID, "全部权限", menuVos));
    }

    @Override
    public AjaxResult roleMenus(long roleId) {
        return AjaxResult.success(baseMapper.roleMenusByRoleId(roleId));
    }

    @Override
    public List<SysMenu> getMenuPermission(Long userId) {
        return baseMapper.getMenuPermission(userId);
    }
}




